#!/usr/bin/env bash
# MJPGstreamer installer
# Builds MJPGstreamer for rPi devices
# Written by Raymond Himle (Adapted from the OctoPi image creation scripts. Thanks Gina and Guysoft!)
# GPL V3
########


# Source error handling, leave this in place
set -x
set -e

source /common.sh
install_cleanup_trap

unpack /filesystem/home/pi /home/pi pi

apt update
apt install -y --allow-downgrades git cmake cmake-data
cd /home/pi
  #mjpg-streamer
  if [ "$MJPGSTREAMER_INCLUDE_MJPGSTREAMER" == "yes" ]
  then
    echo "--- Installing mjpg-streamer"
    if [ $( is_in_apt libjpeg62-turbo-dev ) -eq 1 ]; then
      apt-get -y --force-yes install libjpeg62-turbo-dev
    elif [ $( is_in_apt libjpeg8-dev ) -eq 1 ]; then
      apt-get -y --force-yes install libjpeg8-dev
    fi

    apt-get -y --allow-downgrades --allow-remove-essential --allow-change-held-packages --no-install-recommends install imagemagick ffmpeg libv4l-dev
    gitclone MJPGSTREAMER_MJPGSTREAMER_REPO mjpg-streamer
    pushd mjpg-streamer
      mv mjpg-streamer-experimental/* .

      # As said in Makefile, it is just a wrapper around CMake.
      # To apply -j option, we have to unwrap it.
      MJPG_STREAMER_BUILD_DIR=_build
      [ -d ${MJPG_STREAMER_BUILD_DIR} ] || (mkdir ${MJPG_STREAMER_BUILD_DIR} && \
        chown pi:pi ${MJPG_STREAMER_BUILD_DIR})
      [ -f ${MJPG_STREAMER_BUILD_DIR}/Makefile ] || (cd ${MJPG_STREAMER_BUILD_DIR} && \
        sudo -u pi cmake -DCMAKE${MJPG_STREAMER_BUILD_DIR}_TYPE=Release ..)

      sudo -u pi make -j $(nproc) -C ${MJPG_STREAMER_BUILD_DIR}

      sudo -u pi cp ${MJPG_STREAMER_BUILD_DIR}/mjpg_streamer .
      sudo -u pi find ${MJPG_STREAMER_BUILD_DIR} -name "*.so" -type f -exec cp {} . \;

      # create our custom web folder and add a minimal index.html to it
      sudo -u pi mkdir www-mjpgstreamer
      pushd www-mjpgstreamer
        cat <<EOT >> index.html
<html>
<head><title>mjpg_streamer test page</title></head>
<body>
<h1>Snapshot</h1>
<p>Refresh the page to refresh the snapshot</p>
<img src="./?action=snapshot" alt="Snapshot">
<h1>Stream</h1>
<img src="./?action=stream" alt="Stream">
</body>
</html>
EOT
      popd
    popd
  fi

### mjpg_streamer

unpack /filesystem/root /

if [ "$MJPGSTREAMER_INCLUDE_MJPGSTREAMER" == "yes" ]
then
 systemctl_if_exists enable webcamd.service
else
  rm /etc/logrotate.d/webcamd
  rm /etc/systemd/system/webcamd.service
  rm /root/bin/webcamd
fi

#cleanup
apt-get clean
apt-get autoremove -y

# link logfiles to klipper_logs
ln -s /var/log/webcamd.log /home/pi/klipper_logs/

# Run installation steps defined above

# Unpack root at the end, so files are modified before
unpack /filesystem/root /
